﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using IrisGenerator.Framework.Reflection;
using IrisGenerator.Framework.Events;

namespace IrisGenerator.Framework.UI.Controls
{
    public class BindableToolStripMenuItem<T>:ToolStripMenuItem,IBindableControl
    {

        public BindableToolStripMenuItem()
            : base()
        {
        }

        #region Loading

        

        
        #endregion

        #region IBindableControl Members

        public void LoadSource()
        {
            if (this.SourceMethod != null && !this.DesignMode)
                this.DataSource = GetDataSourceFromMethod();

            this.Text = "Load Project";

            IList items = this.DataSource as IList;
            if(items!=null)
            {
                foreach (T obj in items)
                {
                    CustomToolStripMenuItem<T> item = new CustomToolStripMenuItem<T>();
                    if (!string.IsNullOrEmpty(this.TextDataProperty))
                    {
                        item.Text = Property.GetPropertyValue(obj, this.TextDataProperty) as string;
                        item.Value = obj;
                        item.Click += new EventHandler(item_Click);
                        this.DropDownItems.Add(item);
                    }
                        
                }
            }
        }

        public event EventHandler<BaseEventArgs<T>> SubItemClicked;


        void item_Click(object sender, EventArgs e)
        {
            CustomToolStripMenuItem<T> item = sender as CustomToolStripMenuItem<T>;
            if (item == null)
                return;
            this.OnSubItemClicked(new BaseEventArgs<T>(item.Value,false));
            
        }

        protected void OnSubItemClicked(BaseEventArgs<T> e)
        {
            if (this.SubItemClicked != null)
            {
                SubItemClicked(this, e);
            }
        }



        public string TextDataProperty { get; set; }
        public string TagDataProperty { get; set; }

        private object GetDataSourceFromMethod()
        {
            bool result;
            object tmp = SourceMethod.Invoke(this, out result);
            return tmp;
        }

        public IrisGenerator.Framework.Reflection.MethodCall SourceMethod
        {
            get;
            set;
        }

        public object DataSource { get; set; }

        #endregion
    }
}
